package com.xxxy.dongyexuan.action;

import com.alibaba.fastjson.JSON;
import com.xxxy.dongyexuan.mapper.IUserMapper;
import com.xxxy.dongyexuan.po.User;
import com.xxxy.dongyexuan.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin
public class LoginAction {
    @Autowired
    private IUserMapper mapper;
    //前端请求的登录地址，根据这个地址找到这个方法
    @PostMapping("/dologin")
    //将填写的用户名、密码、验证码带过来，以及用户的唯一标识
    public String  dologin(String uname,String upassword,String biaozhi,String yanzhengma)
        throws Exception{
        //输出填写的用户名+密码+用户标识+验证码
        System.out.println(uname + " " + upassword + " " + biaozhi + " " + yanzhengma);
        //输出填写的客户端验证码
        System.out.println("客户端验证码:" + yanzhengma);
        //调用工具类中的方法获取图片的验证码,赋值给fyanzhengma
        String fyanzhengma = TuAction.codemap.get(biaozhi);
        //输出服务端验证码
        System.out.println("服务器端验证码:" + fyanzhengma);
        //如果客户端输出的验证码等于服务端生成的验证码
        if (yanzhengma.equalsIgnoreCase(fyanzhengma)) {
            //输出验证码验证成功
            System.out.println("验证码验证成功");
            //接下来验证用户名和密码是否一直
            //从数据库中查询用户名、密码给user1
            User user1 = mapper.findUserByUsernameAndPassword(uname, upassword);
            //输出这个user1
            System.out.println(user1);
            //如果user1不为空
            if(user1!=null){
                String str= JSON.toJSONString(user1);
                return JWTUtil.createJWT(str);
            }else{
                //否则抛出异常
                throw new Exception();
            }
        } else {
            //如股票验证码不相同，输出验证失败
            System.out.println("验证码验证失败");
            //抛出异常
            throw new Exception();
        }
    }

}
